package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.MqOpsService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/03/22 12:55
 **/
@Service
@Slf4j
public class MqOpsServiceImpl implements MqOpsService {


    @Autowired
    private AlbumStatMapper albumStatMapper;
    @Autowired
    private TrackStatMapper trackStatMapper;
    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;
    @Autowired
    private TrackInfoMapper trackInfoMapper;


    @Override
    @Transactional
    public void listenAlbumAndTrackStatNumUpdate(TrackStatMqVo trackStatMqVo) {
        // 1.更新专辑的播放量
        // 数量 专辑id 维度
        Long albumId = trackStatMqVo.getAlbumId();
        Integer count = trackStatMqVo.getCount();
        String statType = trackStatMqVo.getStatType();
        try {
            if (albumId != null) {
                // 1.更新专辑的播放量(专辑的播放量、不能修改专辑的收藏量)
                int albumAffectRow = albumStatMapper.updateAlbumStatNum(albumId, statType, count);
                log.info("更新专辑的播放量:{}", albumAffectRow > 0 ? "success" : "fail");
                // 2.更新声音的播放量(声音的播放量(0701))
                Long trackId = trackStatMqVo.getTrackId();
                int trackAffectRow = trackStatMapper.updateTrackStatNum(trackId, SystemConstant.TRACK_STAT_PLAY, count);
                log.info("更新声音的播放量:{}", trackAffectRow > 0 ? "success" : "fail");
            }else {
                // 2.更新声音的收藏量(收藏量(0702))
                Long trackId = trackStatMqVo.getTrackId();
                int trackAffectRow = trackStatMapper.updateTrackStatNum(trackId, statType, count);
                log.info("更新声音的收藏量:{}", trackAffectRow > 0 ? "success" : "fail");
            }

        } catch (Exception e) {
            throw new GuiguException(201, "数据库操作失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void trackStatTypeUpdate(TrackStatMqVo trackStatMqVo) {
        // 1.获取参数
        Long trackId = trackStatMqVo.getTrackId();
        Long albumId = trackStatMqVo.getAlbumId();
        String statType = trackStatMqVo.getStatType();
        Integer count = trackStatMqVo.getCount();
        try {
            if (albumId != null) {
                // 2.更新专辑的播放量（没有收藏量）
                int affectAlbumUpdateRows = albumStatMapper.updateAlbumNumByType(albumId, SystemConstant.ALBUM_STAT_PLAY, count);
                log.info("更新专辑的播放量：{}", affectAlbumUpdateRows > 0 ? "成功" : "失败");
            }
            // 3.更新声音的播放量/收藏量
            int affectTrackUpdateRows = trackStatMapper.updateTrackNumByType(trackId, statType, count);
            log.info("更新声音的播放量：{}", affectTrackUpdateRows > 0 ? "成功" : "失败");
        } catch (Exception e) {
            throw new GuiguException(201, "更新声音的播放量失败");
        }
    }

    @Override
    public void albumStatTypeUpdate(JSONObject jsonObject) {
        String orderNo = (String) jsonObject.get("orderNo");
        Integer userId = (Integer) jsonObject.get("userId");

        // 1.根据订单编号查询订单信息
        Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfoByOrderNo(orderNo, Long.valueOf(userId));
        OrderInfo orderInfoResultData = orderInfoResult.getData();
        Assert.notNull(orderInfoResultData, "远程查询订单微服务获取订单信息失败");

        // 2.获取付款项类型
        String itemType = orderInfoResultData.getItemType();
        Long albumId = null;

        if ("1001".equals(itemType)) {
            // 处理专辑
            albumId = orderInfoResultData.getOrderDetailList().get(0).getItemId();
        } else if ("1002".equals(itemType)) {
            // 处理 声音---修改这个声音对应专辑的购买量
            Long trackId = orderInfoResultData.getOrderDetailList().get(0).getItemId();
            TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
            albumId = trackInfo.getAlbumId();
        } else {
            return;  // vip不用管
        }
        albumStatMapper.updateAlbumNumByType(albumId, "0403", orderInfoResultData.getOrderDetailList().size());
    }
}
